package com.ikas.autumn.iec104.common.handle;

import com.ikas.autumn.iec104.common.enums.GlobalConstants;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

@Controller
public class RequestErrorHandler extends BasicErrorController {

    public RequestErrorHandler(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE));
        HttpStatus status = getStatus(request);

        Map<String, Object> map = new LinkedHashMap<>();
        map.put(GlobalConstants.JSON_RESULT_CODE, status.value());
        if (status.value() == 404) {
            map.put(GlobalConstants.JSON_RESULT_MSG, String.format("%s not found", body.get("path")));
        } else {
            map.put(GlobalConstants.JSON_RESULT_MSG, String.format("%s %s, %s", body.get("path"), body.get("error"), body.get("message")));
        }
        map.put(GlobalConstants.JSON_RESULT_DESC, "ErrorController");
        return new ResponseEntity<>(map, status);
    }
}